Java 执行Linux Command 发表于 2020-05-21 | 分类于 Java | | 阅读次数: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;@RestControllerpublic class ExecuteController { /** * 执行指定命令 */ @RequestMapping(value = "/executeMult", method = RequestMethod.GET) public Object executeMult(String command) throws IOException { if (StringUtils.isEmpty(command)) return "Error Command "; String[] strings = new String[3]; strings[0] = "/bin/sh"; strings[1] = "-c"; strings[2] = command; StringBuffer stringBuffer = new StringBuffer(); int exitValue = -1; BufferedReader bufferedReader = null; try { // command process Process process = Runtime.getRuntime().exec(strings); BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream()); bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); // command log String line; while ((line = bufferedReader.readLine()) != null) { stringBuffer.append(line); stringBuffer.append(System.getProperty("line.separator")); System.out.println(line); } // command exit process.waitFor(); exitValue = process.exitValue(); } catch (Exception e) { e.printStackTrace(); } finally { if (bufferedReader != null) { bufferedReader.close(); } } if (exitValue == 0) { return stringBuffer.toString(); } else { return "command exit value(" + exitValue + ") is failed"; } }} 打赏 微信支付 支付宝